<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="样品编号" prop="sampleName">
        <el-input
            v-model="queryParams.sampleName"
            placeholder="请输入样品编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送样日期" prop="deliveryDate">
        <el-date-picker clearable
                        v-model="queryParams.deliveryDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择送样日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item style="position: absolute;right: 0">
        <el-button
            type="success"
            plain
            @click="router.push('/sample/sitem')"
        >返回
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="!finish">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="!finish">
        <el-button
            type="primary"
            plain
            icon="Edit"
            :disabled="single || !canDo"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="!finish">
        <el-button
            type="primary"
            plain
            icon="Delete"
            :disabled="multiple || !canDo"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="!finish">
        <el-button
            type="primary"
            plain
            icon="Refresh"
            :disabled="flumeAble || !canDo"
            @click="flume"
        >流转
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Download"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <upload-sample :project-id="pid" @refresh="getList"/>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sampleList" style="width: 100%" @selectionChange="handleSelectionChange"
              row-key="sampleId"
              border
              default-expand-all>
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column fixed label="序号"  width=100 type="index" align="center" prop="sampleId" />-->
      <el-table-column label="样品编号" align="center" prop="sampleName" width="200"/>
      <el-table-column label="图片" align="center" prop="sampleImage" width="120">
        <template #default="scope">
          <el-image
              v-if="scope.row.sampleImage"
              style="width: 100px; height: 100px"
              :src="scope.row.sampleImage.split(';')[0]"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.sampleImage.slice(0,-1).split(';')"
              :initial-index="4"
              fit="cover"
              preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="批次/取样时间" align="center" prop="batch" width="200"/>
      <el-table-column label="联系人" align="center" prop="linkman" width="200"/>
      <el-table-column label="流转记录" align="center" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="openSampleLz(scope.row.sampleId)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="样品状态" align="center" prop="sampleStatus" width="120">
        <template #default="scope">
          <div v-if="scope.row.sampleStatus==7"
               style="background-color: #ffc400;color: white;border-radius: 30%;font-size: 12px">
            已制备
          </div>
          <div v-else-if="scope.row.sampleStatus >=2 "
               style="background-color: blue;color: white;border-radius: 30%;font-size: 12px">
            出库
          </div>
          <div v-else-if="scope.row.sampleStatus>-1"
               style="background-color: lawngreen;color: white;border-radius: 30%;font-size: 12px">
            在库
          </div>
          <div v-else style="background-color: red;color: white;border-radius: 30%;font-size: 12px">
            退回
          </div>
        </template>
      </el-table-column>
      <el-table-column label="井号" align="center" prop="wellId"/>
      <el-table-column label="深度(m)" align="center" prop="depth"/>
      <el-table-column label="岩石类型" align="center" prop="rockType" width="150"/>
      <el-table-column label="样品量(g)" width="120" align="center" prop="sampleQuantity"/>
      <el-table-column label="样品尺寸(cm)" align="center" prop="sampleSize" width="120"/>
      <el-table-column label="送样人" align="center" prop="sampleSender"/>
      <el-table-column label="送样形式" align="center" prop="sendingStyle" width="120"/>
      <el-table-column label="送样日期" align="center" prop="deliveryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="senderPhone" width="180"/>
      <el-table-column label="样品备注" align="center" prop="sampleBackup" width="200"/>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <div v-if="scope.row.confirmStatus==0 && scope.row.sampleStatus >=0 && scope.row.sampleStatus <=1">
            <el-button v-if="!finish" link type="success" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-if="!finish" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button v-if="!finish" link type="primary" icon="Refresh" @click="aloneflume(scope.row.sampleId)">流转</el-button>
          </div>
          <div v-if="scope.row.confirmStatus==2 || scope.row.confirmStatus==64">
            <el-button  link type="success" icon="Edit" @click="handleConfirm(scope.row.sampleId,scope.row.confirmStatus)">确认</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改样品对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body style=" border-radius: 20px;padding-right: 10px;padding-left: 10px" class="larger-input">
      <el-form ref="sampleRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="样品编号" prop="sampleName">
          <el-input v-model="form.sampleName" placeholder="请输入样品编号"/>
        </el-form-item>
        <el-form-item label="岩石类型" prop="rockType">
          <el-input v-model="form.rockType" placeholder="请输入岩石类型"/>
        </el-form-item>
        <el-form-item label="井号" prop="wellId">
          <el-input v-model="form.wellId" placeholder="请输入井号"/>
        </el-form-item>
        <el-form-item label="深度(m)" prop="depth">
          <el-input v-model="form.depth" placeholder="请输入深度(m)"/>
        </el-form-item>
        <el-form-item label="样品量(g)" prop="sampleQuantity">
          <el-input v-model="form.sampleQuantity" placeholder="请输入样品量(g)"/>
        </el-form-item>
        <el-form-item label="样品尺寸(cm)" prop="sampleSize">
          <el-input v-model="form.sampleSize" placeholder="请输入样品尺寸(cm)"/>
        </el-form-item>
        <el-form-item label="样品备注" prop="sampleBackup">
          <el-input v-model="form.sampleBackup" placeholder="请输入样品备注"/>
        </el-form-item>
        <el-form-item label="送样人" prop="sampleSender">
          <el-input v-model="form.sampleSender" placeholder="请输入送样人"/>
        </el-form-item>
        <el-form-item label="送样形式" prop="sendingStyle">
          <el-select
              v-model="form.sendingStyle"
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入送样形式"
              style="width: 800px"
          >
            <el-option key="1" label="快递" value="快递"/>
            <el-option key="2" label="人工" value="人工"/>
            <el-option key="3" label="其他" value="其他"/>
          </el-select>
        </el-form-item>
        <el-form-item label="送样日期" prop="deliveryDate">
          <el-date-picker clearable
                          v-model="form.deliveryDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择送样日期"
                          style="width: 800px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系方式" prop="senderPhone">
          <el-input v-model="form.senderPhone" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="批次/取样时间" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入批次/取样时间"/>
        </el-form-item>
        <el-form-item label="联系人" prop="linkman">
          <el-input v-model="form.linkman" placeholder="请输入联系人"/>
        </el-form-item>
        <el-form-item label="样品图片" prop="sampleImage">
          <el-upload
              v-model:file-list="imgs"
              :action="env+'/common/upload'"
              list-type="picture-card"
              :on-remove="removeImg"
              multiple
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  流转  -->
    <el-dialog v-model="openFlume" width="500px" append-to-body style=" border-radius: 20px;">
      <el-form :model="lzform" label-width="100px">
        <el-form-item label="流转到">
          <el-select
              v-model="lzform.circulationType"
              filterable
              placeholder="Select"
              style="width: 500px;max-height: 100px"
          >
            <el-option key="3" label="项目负责人" value="8"/>
            <el-option key="2" label="实验添加员" value="9"/>
          </el-select>
        </el-form-item>
        <el-form-item label="流转意见">
          <el-input
              v-model="lzform.circulationSuggestion"
              type="textarea"
              :rows="3"
              placeholder="请输入流转意见"/>
        </el-form-item>

        <el-form-item style="text-align: center">
          <el-button type="success" @click="submitFlume()">确定</el-button>
          <el-button type="danger" @click="flume()">关闭</el-button>
          <el-button type="info" @click="back">退回样品</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--  流转信息  -->
    <el-dialog v-model="openlz" title="流转记录" width="800px" append-to-body style=" border-radius: 20px;">
      <el-table :data="lzList">
        <el-table-column label="样品编号" prop="sampleName"/>
        <el-table-column label="流转信息" width="150" prop="message"/>
        <el-table-column label="操作人" prop="userName"/>
        <el-table-column label="流转时间" width="160" prop="date"/>
        <el-table-column label="样品量(g)" prop="sampleQuantity"/>
        <el-table-column label="样品尺寸(cm)" prop="sampleSize"/>
      </el-table>
    </el-dialog>
    <!--  退回样品  -->
    <el-dialog v-model="openBack" title="退回样品" width="500px" append-to-body style=" border-radius: 20px;">
      <el-form :model="lzform" :rules="lzRules" ref="backRef">
        <el-form-item label="甲方接收人" prop="userName">
          <el-input v-model="lzform.userName"/>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button type="info" @click="flumeBack()">退回</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>

<script setup>
import {
  listSample,
  getSample,
  delSample,
  addSample,
  updateSample,
  postFlume,
  postFlumeBack,
  listStatus, listLz, checkSampleName, Cconfirm,
} from "@/api/sample/sample.js";
import {parseTime} from "@/utils/ruoyi.js";
import {useRoute} from "vue-router";
import router from "@/router/index.js";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import {deleteImg} from "@/api/experiment/experimentOut.js";
import UploadSample from "@/views/sample/sample/uploadSample.vue";
const env=import.meta.env.VITE_APP_BASE_API
const {proxy} = getCurrentInstance();

const sampleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const flumeAble = ref(true);

const baseurl = import.meta.env.VITE_APP_BASE_API;

const pid = useRoute().query.id;
const finish = useRoute().query.finish == 1;

const data = reactive({
  form: {
    fileList: [],
    projectId: pid,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: pid,
    sampleName: null,
    deliveryDate: null,
  },
  rules: {
    sampleName: [
      {required: true, message: "样品名不能为空", trigger: "blur"}
    ],
    sampleQuantity: [
      {required: true, message: "样品量不能为空", trigger: "blur"}
    ],
    sampleSender: [
      {required: true, message: "送样人不能为空", trigger: "blur"}
    ],
    sendingStyle: [
      {required: true, message: "送样形式不能为空", trigger: "blur"}
    ],
    deliveryDate: [
      {required: true, message: "送样日期不能为空", trigger: "blur"}
    ],
    senderPhone: [
      {required: true, message: "联系方式不能为空", trigger: "blur"}
    ],

  },
  lzform: {
    projectId: pid
  },
  lzRules: {
    userName: [
      {required: true, message: "甲方接收人不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules, lzform, lzRules} = toRefs(data);

const imgs = ref([]);

/** 查询样品列表 */
function getList() {
  loading.value = true;
  listSample(queryParams.value).then(response => {
    console.log(response)
    sampleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    sampleId: null,
    projectId: pid,
    sampleName: null,
    wellId: null,
    depth: null,
    rockType: null,
    sampleQuantity: null,
    sampleSize: null,
    sampleBackup: null,
    sampleSender: null,
    sendingStyle: null,
    deliveryDate: null,
    senderPhone: null,
    sampleStatus: null,
  };
  imgs.value = []
  proxy.resetForm("sampleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

const sampleStatus = ref([]);
//确认状态
const canDo=ref(true);

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.sampleId);
  sampleStatus.value = selection.map(item => item.sampleStatus)
  canDo.value=true;
  for (let e of selection) {
    if (e.confirmStatus!=0){
      canDo.value=false;
      break;
    }
  }
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  flumeAble.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加样品";
}

//删除图片
function removeImg(file) {
  let fileName;
  if (file.response != undefined) {
    fileName = file.response.fileName;
  } else {
    fileName = file.fileName
  }
  deleteImg(fileName);
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _sampleId = row.sampleId || ids.value
  getSample(_sampleId).then(res => {
    form.value = res.data;
    imgs.value = []
    if (res.data.sampleImage != null && res.data.sampleImage != '') {
      var s = res.data.sampleImage.slice(0, -1).split(';')
      for (let img of s) {
        imgs.value.push({fileName: img.slice(img.indexOf('/upload')), url: img})
      }
    }
    open.value = true;
    title.value = "修改样品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sampleRef"].validate(valid => {
    if (valid) {
      let sampleImage = '';
      for (let img of imgs.value) {
        if (img.response != undefined) {
          sampleImage += img.response.url + ';';
        } else {
          sampleImage += img.url + ';';
        }
      }
      form.value.sampleImage = sampleImage;
      if (form.value.sampleId != null) {
        updateSample(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSample(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
        //检验样品编号唯一性
        // checkSampleName(pid, form.value.sampleName).then(res => {
        //   if (res.data) {
        //   } else {
        //     ElMessage({message: '样品编号重复！', type: "warning"});
        //   }
        // })
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _sampleIds = row.sampleId || ids.value;
  proxy.$modal.confirm('是否确认删除样品编号为"' + _sampleIds + '"的数据项？').then(function () {
    return delSample(_sampleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sample/export', {...queryParams.value}, `sample_${new Date().getTime()}.xlsx`)
}

/**  流转   */
const openFlume = ref(false);

function flume() {
  openFlume.value = true;
  lzform.value = {
    projectId: null,
    circulationType: null,
    circulationSuggestion: null,
  }
}

//单独流转
function aloneflume(id) {
  ids.value = [id]
  openFlume.value = true;
  lzform.value = {
    projectId: null,
    circulationType: null,
    circulationSuggestion: null,
  }
}

function submitFlume() {
  if (lzform.value.circulationType == null) {
    ElMessage({
      message: '请选择流转去向',
      type: 'warning'
    })
    return;
  }
  const sids = ids.value;
  listStatus(sids).then(res => {
    for (let status of sampleStatus.value) {
      if (status == -1) {
        ElMessage({
          message: '样品已退回，不可流转',
          type: 'warning'
        })
        return;
      }
      if (status == 7) {
        ElMessage({
          message: '样品已制备，不可流转',
          type: 'warning'
        })
        return;
      }
      if (status >= 2) {
        ElMessage({
          message: '样品已流转，不可重复流转',
          type: 'warning'
        })
        return;
      }
    }
    lzform.value.ids = ids.value;
    lzform.value.projectId = pid;
    postFlume(lzform.value).then(res => {
      if (res.code == 200) {
        getList();
        ElMessageBox.alert('流转成功', '提示', {
          confirmButtonText: 'OK',
          callback: (value, action) => {
            openFlume.value = false;
          }
        })
      }
    })

  })
}

const openBack = ref(false);
const backRef = ref();

function back() {
  openFlume.value = false;
  openBack.value = true;
}

function flumeBack() {
  proxy.$refs["backRef"].validate(valid => {
    if (valid) {
      lzform.value.ids = ids.value;
      postFlumeBack(lzform.value).then(res => {
        if (res.data) {
          getList();
          ElNotification({
            title: '提示',
            message: '退回成功',
            type: 'success',
          })
          openBack.value = false;
        } else {
          getList();
          ElNotification({
            title: '提示',
            message: '退回失败(存在已出库样品)',
            type: 'warning',
          })
          openBack.value = false;
        }
      })
    }
  })
}

/** 流转记录 */

const openlz = ref(false);
const lzList = ref([]);

function openSampleLz(id) {
  listLz(id).then(res => {
    lzList.value = res.data;
    openlz.value = true;
  })
}

/** 确认 */
function handleConfirm(id,status){
  Cconfirm(id).then(res=>{
    if (res.data){
      ElNotification({title:'提示',type:'success',message:'确认成功'})
      getList();
    }
  })
}

getList()
</script>
